/**
 * 测试页的Model 在src/store/index.js中被挂载到store上，命名为test
 * 项目中不同的大模块可以创建不同的js作为model
 * 此model中包含了用于src/container/test模块的数据和方法
 * **/
import { createModel } from '@rematch/core'
import type { RootModel } from '.'
import { IUserInfo, getUserList } from '@/api/mock'

type TestState = {
  fetchvalue: IUserInfo[]
  count: number
}

export const test = createModel<RootModel>()({
  state: {
    count: 0, // 测试数字
    fetchvalue: [] // 异步请求的测试数据
  } as TestState,

  reducers: {
    setCount(state: TestState, payload: number) {
      return { ...state, count: state.count + payload }
    },
    setFetchValue(state: TestState, payload: IUserInfo[]) {
      return { ...state, fetchvalue: payload }
    }
  },

  /** actions **/
  effects: (dispatch) => ({
    // 测试 - 数字加1
    onTestAdd(num: number) {
      dispatch.test.setCount(num) //. 这里会指向上面reducers中的setCount
    },

    // 测试 - 异步请求
    async serverFetch() {
      const { data, statusCode } = await getUserList()
      if (data && statusCode === 200) {
        dispatch({ type: 'test/setFetchValue', payload: data }) // test/setFetchValue对应上面reducers中的setFetchValue
      }
      return data
    }
  })
})
